package top.hzy520.user.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.hzy520.annotation.LogAnnotation;
import top.hzy520.aop.LogAop;
import top.hzy520.common.constants.Constants;
import top.hzy520.common.resp.ApiResult;
import top.hzy520.common.utils.AliyunUploadDown;
import top.hzy520.common.utils.BaseController;
import top.hzy520.dept.entity.Dept;
import top.hzy520.dept.service.DeptService;
import top.hzy520.online.service.OnlineService;
import top.hzy520.role.entity.Role;
import top.hzy520.role.service.RoleService;
import top.hzy520.user.dto.SearchUserDto;
import top.hzy520.user.dto.SearchUserInputDto;
import top.hzy520.user.entity.User;
import top.hzy520.common.page.Pagination;
import top.hzy520.user.service.UserService;

import javax.servlet.http.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 20:53 2018/7/24
 */
@Controller
public class UserController extends BaseController {
  SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;

    @Autowired
    @Qualifier("onlineServiceImpl")
    private OnlineService onlineService;

    @Autowired
    @Qualifier("roleServiceImpl")
    private RoleService roleService;

    @Autowired
    @Qualifier("deptServiceImpl")
    private DeptService deptService;
    @RequestMapping("/")
    public String empty(Model model){
        User user= getCurrentUser();
        if (user!=null){
            Dept dept= deptService.selectDeptById(user.getDeptId());
            user.setDept(dept);
            model.addAttribute("user",user);
        }
        return "index";}
    @RequestMapping("/index")
    public String index(Model model){
        User user= getCurrentUser();
       Dept dept= deptService.selectDeptById(user.getDeptId());
        user.setDept(dept);
        model.addAttribute("user",user);
        return "index";
    }

    @LogAnnotation(value = Constants.LOGIN_LOG_NAME)
    @ResponseBody
    @RequestMapping(value = "/user/login",method = {RequestMethod.POST})
   public ApiResult userLogin(@RequestBody User user){
        ApiResult apiResult=new ApiResult(Constants.RESP_STATUS_OK,"登录成功");
        UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword(),user.isRememberMe());
        Subject subject=SecurityUtils.getSubject();
        try {
              subject.login(token);
              subject.getSession().setTimeout(1800000);
              //登录成功插入在线用户表
            onlineService.saveOnlineUser(user.getUsername(),String.valueOf(subject.getSession().getId()),LogAop.getServletRequest());
        }catch (Exception e){
            apiResult.setCode(Constants.RESP_STATUS_INTERNAL_ERROR);
            apiResult.setMessage("登录失败");
              return apiResult;
        }
        return apiResult;
   }
    @RequestMapping(value = "/user")
    public String adduser(){
        return "admin/user/user";
    }
    @RequiresPermissions("system:user:view")
    @RequestMapping("/user/list")
    @ResponseBody
    public Pagination selectAllUser(Integer limit, Integer offset, String departmentname, String statu, String search){
       List<User> userList=userService.selectAllUser(offset,limit);
       int count=userService.selectAllcount();
         Pagination userPage=new Pagination();
         userPage.setTotal(count);
         userPage.setRows(userList);
       return userPage;
    }
    @RequestMapping("/user/refreshlist/{id}")
    @ResponseBody
    public Pagination refresh(int limit, int offset, @PathVariable("id") Long id){
        List<User> userList=userService.selectAllUserById(offset,limit,id);
        int count=userService.selectAllcountById(id);
        Pagination userPage=new Pagination();
        userPage.setTotal(count);
        userPage.setRows(userList);
        return userPage;
    }
    @LogAnnotation(value =Constants.OPERATION_LOG_NAME ,operationNmae = Constants.EDIT_USER_LOG_NAME)
    @ResponseBody
    @RequestMapping(value = "/user/editpost/{roleId}",method = {RequestMethod.POST})
    public ApiResult editPost(@RequestBody User user,@PathVariable("roleId") Long roleId){
        userService.updataUser(user);
        roleService.updateUserRole(roleId,user.getId());
        ApiResult apiResult=new ApiResult(Constants.RESP_STATUS_OK,"编辑成功");
       return apiResult;
    }
    @RequestMapping("/add")
    public String addUser(Model model){
        List<Role> roleList=roleService.selectRole();
        model.addAttribute("roleList",roleList);
        return "admin/user/add";
    }
    @RequestMapping("/user/edit/{id}")
    public String edit(@PathVariable("id") Long id, Model model){
     User user=userService.selectUserByUserId(id);
        List<Role> roleList=roleService.selectRole();
        model.addAttribute("roleList",roleList);
      model.addAttribute("user",user);
        return "admin/user/edit";
    }
    @LogAnnotation(value =Constants.OPERATION_LOG_NAME ,operationNmae = Constants.DELETE_SINGLE_USER_LOG_NAME)
    @ResponseBody
    @RequestMapping(value = "/user/delete",method = {RequestMethod.POST})
    public ApiResult deleteUser(@RequestBody User user){
        userService.deleteUser(user.getId());
        ApiResult apiResult=new ApiResult(Constants.RESP_STATUS_OK,"删除成功");
        return apiResult;
    }
    @ResponseBody
    @RequestMapping(value = "/user/deleteall",method = {RequestMethod.POST})
    public ApiResult deleteAllUser(@RequestBody List<User> userList){
        userService.deleteAllUser(userList);
        ApiResult apiResult=new ApiResult(Constants.RESP_STATUS_OK,"删除成功");
        return apiResult;
    }
    @LogAnnotation(value =Constants.OPERATION_LOG_NAME ,operationNmae = Constants.ADD_USER_LOG_NAME)
    @ResponseBody
    @RequestMapping(value = "/user/adduser/{roleId}",method = {RequestMethod.POST})
    public ApiResult addUser(@RequestBody User user,@PathVariable("roleId") Long roleId){
        roleService.insertRole(roleId, userService.insertUser(user));
        ApiResult apiResult=new ApiResult(Constants.RESP_STATUS_OK,"添加成功");
        return apiResult;
    }
        @ResponseBody
        @RequestMapping(value = "/user/searchuser",method = {RequestMethod.GET})
        public Pagination searchUser(SearchUserInputDto searchUserInputDto) throws ParseException {
            SearchUserDto searchUserDto=new SearchUserDto();
            searchUserDto.setId(searchUserInputDto.getId());
            searchUserDto.setLimit(searchUserInputDto.getLimit());
            searchUserDto.setOffset(searchUserInputDto.getOffset());
        if (searchUserInputDto.getRealName()!=""){
            searchUserDto.setRealName(searchUserInputDto.getRealName());
        }
        if (searchUserInputDto.getStatus()!=""){
            searchUserDto.setStatus(Byte.parseByte(searchUserInputDto.getStatus()));
        }
        if (searchUserInputDto.getStartDate()!=""){
            searchUserDto.setStartDate(format.parse(searchUserInputDto.getStartDate()));
        }
        if (searchUserInputDto.getEndDate()!=""){
            searchUserDto.setEndDate(format.parse(searchUserInputDto.getEndDate()));
        }
        List<User> userList=userService.selectUserBySearch(searchUserDto);
         int count=userService.selectCountBySearch(searchUserDto);
        Pagination userPage=new Pagination();
        userPage.setRows(userList);
        userPage.setTotal(count);
        return userPage;
    }
    @RequestMapping("/logout")
    public String logout(){
        onlineService.forceLogout(String.valueOf(SecurityUtils.getSubject().getSession().getId()));
      SecurityUtils.getSubject().logout();
      return "redirect:/login";
    }
    @RequestMapping("/user/check")
    @ResponseBody
    public ApiResult check(){
        ApiResult apiResult=new ApiResult(Constants.RESP_STATUS_OK,"检查成功");
      User user= getCurrentUser();
     if (user==null){
         apiResult.setCode(Constants.RESP_STATUS_INTERNAL_ERROR);
     }
      return apiResult;
    }
    @RequestMapping("/user/profile")
    public String profile(Model model){
      User user= getCurrentUser();
      model.addAttribute("user",user);
       return "admin/user/profile/profile";
    }
    @RequestMapping("/user/profile/edit")
    public String profileEdit(Model model){
        User user= getCurrentUser();
        List<Role> roleList=roleService.selectRole();
        model.addAttribute("roleList",roleList);
        model.addAttribute("user",user);
        return "admin/user/profile/edit";
    }
    @ResponseBody
    @RequestMapping(value = "/user/editprofile/{roleId}",method = {RequestMethod.POST})
    public ApiResult editProfile(@RequestBody User user,@PathVariable("roleId") Long roleId){
        userService.updataUser(user);
        roleService.updateUserRole(roleId,user.getId());
       User userAfterEdit= userService.selectUserByUserId(user.getId());
       SecurityUtils.getSubject().getSession().setAttribute("user",userAfterEdit);
        ApiResult apiResult=new ApiResult(Constants.RESP_STATUS_OK,"编辑成功");
        return apiResult;
    }

    @RequestMapping("/user/profile/checkPassword")
    @ResponseBody
    public boolean passwordCheck(String password){
        boolean checkResult=userService.passwordCheck(password);
          return checkResult;
    }
    @RequestMapping("/profile/resetPwd")
    public String profileResetPwd(Model model){
       User currentUser= getCurrentUser();
           model.addAttribute("user",currentUser);
        return "admin/user/profile/resetPwd";
    }
    @PostMapping("/user/profile/resetPwd")
    @ResponseBody
    public ApiResult resetPwd(String password){
       User currentUser= getCurrentUser();
        userService.resetPwd(currentUser,password);
    ApiResult apiResult=new ApiResult(Constants.RESP_STATUS_OK,"修改密码成功");
    return apiResult;
    }

    @PostMapping("user/profile/updateAvatar")
    @ResponseBody
    public ApiResult updateAvatar(@RequestParam("avatarfile") MultipartFile file) throws Exception {
    ApiResult apiResult=new ApiResult(Constants.RESP_STATUS_OK,"更新成功");
     String url=   AliyunUploadDown.picOSS(file);
    return apiResult;
    }
}
